package com.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dao.ArticleCommentDAO;
import com.model.ArticleComment;
@Repository
public class ArticleCommentDAOImpl implements ArticleCommentDAO {
	@Autowired
    private SessionFactory sessionFactory;
	
	public void add(ArticleComment comment) {
		sessionFactory.getCurrentSession().save(comment);
	}

	public void addAgree(int id) {
		Session s = sessionFactory.getCurrentSession();
		String hql = "update ArticleComment as c set c.agreeNum=c.agreeNum+1 where c.id=:id";
		Query q = s.createQuery(hql);
		q.setInteger("id", id);
		q.executeUpdate();	
	}

	public void addDisagree(int id) {
		Session s = sessionFactory.getCurrentSession();
		String hql = "update ArticleComment as c set c.disagreeNum=c.disagreeNum+1 where c.id=:id";
		Query q = s.createQuery(hql);
		q.setInteger("id", id);
		q.executeUpdate();	
	}

	@SuppressWarnings("unchecked")
	public List findByPage(int articleId, int page,
			int pageSize) {
		Session s = sessionFactory.getCurrentSession();
		String hql = "select c.*,u.id as user_id,u.name as user_name,u.head_img as user_head from article_comment c inner join user u on u.id=c.user_id where c.article_id=:articleId order by c.create_at desc";
		
		Query query = s.createSQLQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		query.setInteger("articleId", articleId);
		query.setMaxResults(pageSize);
		query.setFirstResult((page-1)*pageSize);
		
		return query.list();
	}

}
